package com.example.demo.mapper;

import com.example.demo.model.UserBehavior;
import com.example.demo.model.recommendation.UserSimilarity;
import org.apache.ibatis.annotations.*;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Map;

// UserBehaviorMapper.java
@Mapper
public interface UserBehaviorMapper {
    // 在 UserBehaviorMapper.java 中添加
    @Insert("INSERT INTO user_behavior (user_id, torrent_id, behavior_type, created_at) " +
            "VALUES (#{user.id}, #{torrent.id}, #{behaviorType}, #{createdAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(UserBehavior userBehavior);

    @Select("SELECT * FROM user_behavior WHERE user_id = #{userId} ORDER BY created_at DESC LIMIT #{limit}")
    List<UserBehavior> findRecentByUser(@Param("userId") Long userId, @Param("limit") int limit);

    // 根据Torrent ID查询相关行为记录
    @Select("SELECT * FROM user_behavior WHERE torrent_id = #{torrentId}")
    List<UserBehavior> findByTorrentId(@Param("torrentId") Long torrentId);

    // 新增：获取用户行为矩阵
    @Select("SELECT user_id, torrent_id FROM user_behavior")
    List<Map<String, Long>> getUserItemMatrix();

    // 新增：获取用户的所有行为记录
    @Select("SELECT * FROM user_behavior WHERE user_id = #{userId}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "user", column = "user_id", one = @One(select = "com.example.demo.mapper.UserMapper.findById")),
            @Result(property = "torrent", column = "torrent_id", one = @One(select = "com.example.demo.mapper.TorrentMapper.findById")),
            @Result(property = "behaviorType", column = "behavior_type"),
            @Result(property = "createdAt", column = "created_at")
    })
//    List<UserBehavior> findByUserId(@Param("userId") Long userId);
    List<UserBehavior> findByUserId(Long userId);

    // 新增：获取用户之间的相似度
    @Select("SELECT user_id1, user_id2, similarity FROM user_similarity WHERE user_id1 = #{userId} OR user_id2 = #{userId}")
    @Results({
            @Result(property = "userId1", column = "user_id1"),
            @Result(property = "userId2", column = "user_id2"),
            @Result(property = "similarity", column = "similarity")
    })
//    List<UserSimilarity> findSimilaritiesByUser(@Param("userId") Long userId);
    List<UserSimilarity> findSimilaritiesByUser(Long userId);
}